package uk.org.mygrid.eobesity.csvserver.routes;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.log4j.Logger;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Parameter;
import org.restlet.data.Status;
import org.restlet.ext.fileupload.RestletFileUpload;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;

public class DatasetUpload extends ServerResource {

    private static Logger logger = Logger.getLogger(DatasetUpload.class);
    private Configuration config;
    
	@Post
	public void uploadDataset() {
		
		Form form = getRequest().getResourceRef().getQueryAsForm();
		Parameter first = form.getFirst("filename");
		
        try {
            setConfig(new PropertiesConfiguration("csv.properties"));
        } catch (ConfigurationException e1) {
            logger.error("Could not create property file ", e1);
        }
        
        String fileDirectory = getConfig().getString("RTFSearcher.0");

		if (MediaType.MULTIPART_FORM_DATA.equals(getRequestEntity()
				.getMediaType(), true)) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(1000240);

            RestletFileUpload upload = new RestletFileUpload(factory);
            List<FileItem> items;
            try {

                items = upload.parseRequest(getRequest());


                boolean found = false;
                for (final Iterator<FileItem> it = items.iterator(); it
                        .hasNext()
                        && !found;) {
                    FileItem fi = it.next();
                    if (fi.getFieldName().equals("dataset")) {
                        found = true;
                        File file = new File(fileDirectory, first.getValue());
                        fi.write(file);
                    }
                }

                Representation rep = null;

                    rep = new StringRepresentation("file uploaded",
                            MediaType.TEXT_PLAIN);

                getResponse().setEntity(rep);
                getResponse().setStatus(Status.SUCCESS_OK);
            } catch (Exception e) {
                getResponse().setEntity(
                        new StringRepresentation(e.getMessage(),
                                MediaType.TEXT_PLAIN));
                getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
                e.printStackTrace();
            }

		}
	}
	
    public void setConfig(Configuration config) {
        this.config = config;
    }

    public Configuration getConfig() {
        return config;
    }

}
